﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MulticastService
{
    public class StructureMatrix
    {
        public int n;
        public int k;
        public int[,] data;

        public static StructureMatrix DefaultStructureMetrix(int _k, int _n)
        {
            StructureMatrix sm = new StructureMatrix();
            sm.n = _n;
            sm.k = _k;
            sm.data = new int[sm.k + 1, sm.n + 1];
            //暂时缺少n>k时的结构矩阵生成算法
            if (sm.n > sm.k)
                throw new Exception();
            else
            {
                for (int i = 1; i <= sm.k; i++)
                {
                    for (int j = 1; j <= sm.n; j++)
                    {
                        int t = i % sm.n == 0 ? sm.n : i % sm.n;
                        if (i <= sm.k - (sm.k % sm.n))
                        {
                            if (t == j)
                                sm.data[i, j] = 0;
                            else
                                sm.data[i, j] = t;
                        }
                        else
                            sm.data[i, j] = j - 1;
                    }
                }
            }
            return sm;
        }

        public string MatirxString()
        {
            string s = "";
            for (int i = 1; i <= k; i++)
            {
                for (int j = 1; j <= n; j++)
                {
                    s += data[i, j].ToString() + "\t";
                }
                s += "\n";
            }
            return s;
        }

        public bool ValidateRegular()
        {
            int[] number_of_sub = new int[n + 1];
            for (int i = 1; i <= k; i++)
            {
                for (int j = 1; j <= n; j++)
                {
                    number_of_sub[data[i, j]]++;
                }
            }
            foreach (int i in number_of_sub)
                if (i > k)
                    return false;
            return true;
        }

        public bool ValidateMulticast()
        {
            for (int i = 1; i < n; i++)
            {
                for (int j = 1; j <= k; j++)
                {
                    int source = i;
                    for (int m = 1; m < k && source > 0; m++)
                    {
                        source = data[j, source];
                    }
                    if (source != 0)
                    {
                        Console.WriteLine("stream{0} of peer{1} is not from out structure", j, i);
                        return false;
                    }
                }
            }
            return true;
        }
    }
}
